package com.group.util;

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.group.dao.GeneralBeanDao;
import com.group.model.FileMap;
import com.group.model.JsTicket;
import com.group.model.SystemPara;
import com.group.model.VerifyCode;

import sun.misc.BASE64Encoder;

@Service
public class WeiXinUtils {
	private static final Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);

	@Autowired
	GeneralBeanDao beanDao;

	@Value("${wx.imageDir:image/}")
	public String imageDir;

	/**
	 * 发送邮件的用户名
	 */
	@Value("${email.username}")
	protected String username;

	/**
	 * 发送邮件的密码
	 */
	@Value("${email.password}")
	protected String password;

	/**
	 * 邮件发送协议
	 */
	@Value("${email.smtpHost}")
	protected String smtpHost;

	/**
	 * 发送人
	 */
	@Value("${email.address}")
	protected String address;

	/**
	 * 发送人
	 */
	@Value("${email.userEmail}")
	protected String userEmail;

	/**
	 * 系统运行环境
	 */
	@Value("${wx.env}")
	protected String env;

	private String weccTokenExceptionSend = "";

	/**
	 * result写入response
	 * 
	 * @param result
	 * @param response
	 */
	public static void write(String result, HttpServletResponse response) {
		try {
			OutputStream outputStream;
			outputStream = response.getOutputStream();
			outputStream.write(result.getBytes("utf-8"));
			outputStream.flush();
		} catch (IOException e) {

			e.printStackTrace();
			throw new NoteException("response 写入失败");
		}
	}

	/**
	 * MD5 加密
	 * 
	 * @param str
	 * @return
	 */
	public static String getMD5Code(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			String result = bytetoString(md.digest(str.getBytes()));
			return result;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new NoteException("加密失败");
		}
	}

	/**
	 * url解码
	 * 
	 * @param url
	 * @return
	 */
	public static String urlDecode(String url) {
		try {
			return URLDecoder.decode(url, "utf8");
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoteException("url解码错误, url = " + url);
		}

	}

	/**
	 * get方式调用url
	 * 
	 * @param url
	 * @return
	 */
	public static String get(String url) {
		String responseString = "";
		try {
			InputStream instr = getForInputstream(url);
			responseString = StreamUtils.copyToString(instr, Charset.forName("utf-8"));
			instr.close();
			logger.info("get url = " + url + " \n response = " + responseString);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoteException(e.getLocalizedMessage());
		}

		return responseString;
	}

	/**
	 * get方式调用url
	 * 
	 * @param src
	 * @return
	 */
	public static InputStream getForInputstream(String src) {
		InputStream instr = null;
		try {
			HttpURLConnection con = getForConnection(src);
			instr = con.getInputStream();

		} catch (Exception e) {
			e.printStackTrace();
			throw new NoteException(e.getLocalizedMessage());
		}

		return instr;
	}

	/**
	 * get方式获取url结果
	 * 
	 * @param src
	 * @return
	 * @throws Exception
	 */
	public static HttpURLConnection getForConnection(String src) throws Exception {
		URL url = new URL(src);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		urlCon.setDoOutput(true);
		urlCon.setDoInput(true);
		urlCon.setUseCaches(true);
		urlCon.setReadTimeout(15000);
		urlCon.setConnectTimeout(15000);
		urlCon.setRequestMethod("GET");
		// 302不自动跳转
		// urlCon.setInstanceFollowRedirects(false);
		// System.out.println(urlCon.getRequestProperty("Cookie"));
		// System.out.println(urlCon.getRequestProperty("set-cookie"));
		// System.out.println(urlCon.getRequestProperty("origin"));
		// System.out.println(urlCon.getRequestProperty("referer"));
		// urlCon.setRequestProperty("Cookie",
		// "__cfduid=d0cf7e4f7fcf2de989f06771af79427261515412780");
		// urlCon.setRequestProperty("Host","coinmarketcap.com");
		// urlCon.setRequestProperty("origin","https://coinmarketcap.com");
		// urlCon.setRequestProperty("referer","https://coinmarketcap.com/currencies/");
		System.out.println(urlCon.getRequestProperties());

		urlCon.connect();
		return urlCon;
	}

	/**
	 * sha1加密
	 * 
	 * @param sha1
	 * @return
	 * @throws Exception
	 */
	public String sha1(String sha1) throws Exception {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		byte[] resultbyte = md.digest(sha1.getBytes());

		return bytetoString(resultbyte);
	}

	public static String bytetoString(byte[] digest) {
		String str = "";
		String tempStr = "";

		for (int i = 0; i < digest.length; i++) {
			tempStr = (Integer.toHexString(digest[i] & 0xff));
			if (tempStr.length() == 1) {
				str = str + "0" + tempStr;
			} else {
				str = str + tempStr;
			}
		}
		return str.toLowerCase();
	}

	/**
	 * 存储文件
	 * 
	 * @param is
	 * @param dir
	 * @param name
	 *            文件名,用于取格式
	 * @return
	 */
	public static String saveTo(InputStream is, String name, String dir) {
		if (is == null)
			return "";

		if (!dir.endsWith(File.separator))
			dir += File.separator;

		String fileName = UUID.randomUUID().toString() + "." + getExt(name);

		try {
			FileOutputStream fos = FileUtils.openOutputStream(new File(dir + fileName));
			IOUtils.copy(is, fos);

			is.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fileName;
	}

	/**
	 * 获取图片
	 * 
	 * @param fileId
	 * @return
	 */
	public File getImage(String fileId) {
		return new File(imageDir + fileId);
	}

	/**
	 * 获取网络图片,保存到本地,返回fileId
	 * 
	 * @param imgSrc
	 * @return
	 */
	public String getNetImage(String imgSrc) {
		if (StringUtils.isEmpty(imgSrc))
			return null;
		InputStream is = getForInputstream(imgSrc);
		return saveTo(is, "qrcode.jpg", imageDir);
	}

	public static String getExt(String fileName) {
		try {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		} catch (Exception e) {
			// 如果用户没输入后缀则默认jpg
			return "jpg";
		}
	}

	/**
	 * 立即post
	 * 
	 * @param json
	 * @param urlstr
	 * @return
	 */
	public String postNow(String json, String urlstr) {
		try {
			InputStream instr = postForInputStream(json, urlstr);
			String ResponseString = StreamUtils.copyToString(instr, Charset.forName("utf-8"));
			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
				System.out.println("返回空");
			}
			logger.info("postjson=" + json + "&&&返回数据为:" + ResponseString);
			instr.close();
			return ResponseString;
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoteException("post失败,url = " + urlstr);
		}
	}

	/**
	 * post请求,参数传map
	 * 
	 * @param json
	 * @param url
	 * @return
	 */
	public static String post(Map<String, String> json, String url) {
		return post(JSONObject.toJSONString(json), url);
	}

	/**
	 * 通用post请求
	 * 
	 * @param json
	 * @param url
	 * @return
	 */
	public static String post(String json, String url) {
		InputStream instr = postForInputStream(json, url);
		try {

			String ResponseString = StreamUtils.copyToString(instr, Charset.forName("utf-8"));
			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
				System.out.println("返回空");
			}
			logger.info("postjson=" + json + "&&&返回数据为:" + ResponseString);
			instr.close();
			return ResponseString;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new NoteException("读取post返回inputstream错误");
		}
	}

	/**
	 * post请求,返回inputstream
	 * 
	 * @param json
	 * @param url
	 * @return
	 */
	public static InputStream postForInputStream(String json, String url) {
		try {
			InputStream instr = postForUrlConnection(json, url).getInputStream();

			return instr;
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoteException("post失败,url = " + url);
		}
	}

	/**
	 * post 并且返回完整结果
	 * 
	 * @param json
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection postForUrlConnection(String json, String url) throws IOException {
		HttpURLConnection urlCon = (HttpURLConnection) new URL(url).openConnection();
		urlCon.setDoOutput(true);
		urlCon.setDoInput(true);
		urlCon.setUseCaches(false);
		urlCon.setConnectTimeout(10000);
		urlCon.setReadTimeout(10000);
		urlCon.setRequestMethod("POST");
		urlCon.setRequestProperty("Content-Type", "application/json;charset=utf-8");
		// urlCon.setRequestProperty("Content-length",String.valueOf(json.length()));
		urlCon.connect();
		DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
		printout.write(json.getBytes());
		printout.flush();
		printout.close();

		return urlCon;
	}

	/**
	 * 八爪鱼数据请求
	 * 
	 * @param para
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String bjyPost(String para, String url, String token) throws Exception {
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		conn.setRequestMethod("POST");// 提交模式
		// conn.setConnectTimeout(10000);//连接超时 单位毫秒
		// conn.setReadTimeout(2000);//读取超时 单位毫秒
		conn.setDoOutput(true);// 是否输入参数
		conn.setRequestProperty("Authorization", "bearer " + token);

		// 表单参数与get形式一样
		byte[] bypes = para.toString().getBytes();
		conn.getOutputStream().write(bypes);// 输入参数
		InputStream inStream = conn.getInputStream();
		String responseString = StreamUtils.copyToString(inStream, Charset.forName("utf-8"));
		inStream.close();
		return responseString;
	}

	/**
	 * 带socks代理的post
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String formPost(String urlstr, String para) throws Exception {
		// InetSocketAddress inetSocketAddress = new
		// InetSocketAddress("192.168.100.1", 1080);
		// InetSocketAddress inetSocketAddress = new
		// InetSocketAddress("121.43.161.198", 8888);
		// Proxy proxy = new Proxy(Proxy.Type.SOCKS, inetSocketAddress);

		URL url = new URL(urlstr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// conn.setInstanceFollowRedirects(false);
		conn.setRequestMethod("POST");// 提交模式
		conn.setConnectTimeout(10000);// 连接超时 单位毫秒
		conn.setReadTimeout(10000);// 读取超时 单位毫秒
		conn.setDoOutput(true);// 是否输入参数
		// conn.setRequestProperty("Referer",
		// "https://www.bcex.ca/market?symbol=czr2eth");
		// conn.setRequestProperty("Host", "www.bcex.ca");
		// conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0;
		// Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
		// Chrome/64.0.3282.140 Safari/537.36");

		StringBuffer params = new StringBuffer();
		// 表单参数与get形式一样
		params.append(para);
		byte[] bypes = params.toString().getBytes();
		conn.getOutputStream().write(bypes);// 输入参数
		// conn.getOutputStream().close();
		InputStream inStream = conn.getInputStream();
		String responseString = StreamUtils.copyToString(inStream, Charset.forName("utf-8"));
		inStream.close();
		return responseString;
	}

	/**
	 * 带代理的get
	 * 
	 * @param urlstr
	 * @return
	 */
	public static String proxyGet(String urlstr) {
		InetSocketAddress inetSocketAddress = new InetSocketAddress("47.75.169.87", 8888);
		Proxy proxy = new Proxy(Proxy.Type.HTTP, inetSocketAddress);

		InputStream inStream = null;
		try {
			URL url = new URL(urlstr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
			conn.setRequestMethod("GET");// 提交模式
			conn.setConnectTimeout(10000);// 连接超时 单位毫秒
			conn.setReadTimeout(10000);// 读取超时 单位毫秒
			conn.setDoOutput(true);// 是否输入参数

			inStream = conn.getInputStream();
			String responseString = StreamUtils.copyToString(inStream, Charset.forName("utf-8"));

			conn.disconnect();
			return responseString;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			return e.getMessage();
		} finally {
			if (inStream != null)
				try {
					System.out.println("关闭连接");
					inStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	/**
	 * 八爪鱼get
	 * 
	 * @param url
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static String bjyGet(String url, String token) throws Exception {

		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		conn.setRequestMethod("GET");// 提交模式
		conn.setConnectTimeout(10000);// 连接超时 单位毫秒
		conn.setReadTimeout(2000);// 读取超时 单位毫秒
		conn.setDoOutput(true);// 是否输入参数
		conn.setRequestProperty("Authorization", "bearer " + token);

		InputStream inStream = conn.getInputStream();
		String responseString = StreamUtils.copyToString(inStream, Charset.forName("utf-8"));
		return responseString;
	}

	public static HttpURLConnection postForUrlConnection(Map<?, ?> json, String url) throws IOException {
		return postForUrlConnection(JSONObject.toJSONString(json), url);
	}

	/**
	 * 发送邮件
	 * 
	 * @param content
	 * @param title
	 */
	public void sendEmail(String content, String title) {
		for (String uEmail : userEmail.split(",")) {
			try {
				HtmlEmail email = new HtmlEmail(); // 发送HTML形式的邮件
				email.setHostName(smtpHost);// 邮件服务器
				email.setAuthentication(username, password);// smtp认证的用户名和密码
				email.addTo(uEmail);// 收信者
				email.setFrom(address, "小纸条公众号");// 发信者
				email.setSubject(env + " Exception Message :" + title);// 标题
				email.setCharset("UTF-8");// 编码格式

				email.setHtmlMsg(content);
				email.send();// 发送
			} catch (EmailException e) {
				// e.printStackTrace();
				// throw new NoteException(e.getLocalizedMessage());
			}
		}
	}

	/**
	 * 发送带附件的邮件
	 * 
	 * @param files
	 * @param users
	 *            发送用户,逗号分隔
	 * @throws Exception
	 */
	public void sendEmailAttachFile(List<File> files, String users) throws Exception {
		HtmlEmail email = new HtmlEmail(); // 发送HTML形式的邮件
		email.setHostName(smtpHost);// 邮件服务器
		email.setAuthentication(username, password);// smtp认证的用户名和密码
		for (String user : users.split(",")) {
			email.addTo(user);// 收信者
		}
		email.setFrom(address, "新势财富");// 发信者
		email.setSubject("产品资料");// 标题
		email.setCharset("UTF-8");// 编码格式

		email.setHtmlMsg("见附件");

		MimeMultipart mainPart = new MimeMultipart();

		for (File file : files) {
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.attachFile(file);
			BASE64Encoder enc = new BASE64Encoder();
			// 获取文件名
			String filename = file.getName();

			FileMap fm = beanDao.quickQueryOne(FileMap.class, "fileId", file.getName());
			if (fm != null)
				filename = fm.getFilename();

			messageBodyPart.setFileName("=?GBK?B?" + enc.encode(filename.getBytes("GBK")) + "?=");
			mainPart.addBodyPart(messageBodyPart);
		}
		email.addPart(mainPart);

		email.send();// 发送

	}

	/**
	 * 发送手机验证码
	 * 
	 * @param phoneNumber
	 */
	public Integer sendVerifyCode(String phoneNumber) {
		// 作废旧的验证码
		beanDao.quickDelete(VerifyCode.class, "phoneNumber", phoneNumber);

		// 添加新的验证码
		VerifyCode vc = new VerifyCode();
		vc.setPhoneNumber(phoneNumber);
		Random r = new Random();
		Integer code = (r.nextInt(9) + 1) * 1000 + r.nextInt(1000);
		vc.setCode(code);
		beanDao.save(vc);

//		SmsApi.send("验证码：" + code + "【wecc】", phoneNumber);
		SmsApi.send(code+"", phoneNumber);
		return code;
	}

	// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	// -------------------------------------------------------------微信token相关---------------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	// -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

	// token过期时间
	private Integer jsExpireTime = null;

	private String jsToken = null;
	// token创建时间
	private Date jsTokenTime = null;

	// token过期时间
	private Integer weccjsExpireTime = null;

	private String weccjsToken = null;
	// token创建时间
	private Date weccjsTokenTime = null;
	// public String getToken() {
	// return
	// JSONObject.parseObject(get("http://http://47.97.169.104:8082/wx/token")).getString("value");
	//
	// }

	/**
	 * 获取token
	 * 
	 * @return
	 */
	public String getToken() {
		SystemPara sp = beanDao.quickQueryOne(SystemPara.class, "name", "access_token");
		String value = sp.getValue();
		// 如果当前存在token并且未过期,返回token
		if (StringUtils.isNotEmpty(value)) {
			String token = value.split(",")[0];
			// token过期时间
			Integer expireTime = Integer.parseInt(value.split(",")[1]);
			// token创建时间
			Date tokenTime = sp.getUpdateTime();

			Integer existTime = new Long((new Date().getTime() - tokenTime.getTime()) / 1000).intValue();
			//
			if (existTime < (expireTime - 200))
				return token;
		}

		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinConf.APPID + "&secret=" + WeiXinConf.SECRET;
		String json = get(url);
		JSONObject object = JSONObject.parseObject(json);
		sp.setValue(object.getString("access_token") + "," + Integer.parseInt(object.getString("expires_in")));
		sp.setUpdateTime(new Date());
		beanDao.save(sp);

		return object.getString("access_token");
	}

	/**
	 * 获取wecc服务号的token
	 * 
	 * @return
	 */
	public String getWeccToken1() {
		SystemPara sp = beanDao.quickQueryOne(SystemPara.class, "name", "wecc_access_token");
		String value = sp.getValue();
		// 如果当前存在token并且未过期,返回token
		if (StringUtils.isNotEmpty(value)) {
			String token = value.split(",")[0];
			// token过期时间
			Integer expireTime = Integer.parseInt(value.split(",")[1]);
			// token创建时间
			Date tokenTime = sp.getUpdateTime();

			Integer existTime = new Long((new Date().getTime() - tokenTime.getTime()) / 1000).intValue();
			//
			if (existTime < (expireTime - 200))
				return token;
		}

		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinConf.WECCAPPID + "&secret=" + WeiXinConf.WECCSECRET;

		String json = get(url);
		JSONObject object = JSONObject.parseObject(json);
		sp.setValue(object.getString("access_token") + "," + Integer.parseInt(object.getString("expires_in")));
		sp.setUpdateTime(new Date());
		beanDao.save(sp);

		return object.getString("access_token");
	}

	/**
	 * 获取js_token
	 * 
	 * @return
	 */
	public String getWeccJsToken1() {
		// 如果当前存在token并且未过期,返回token
		if (weccjsToken != null && weccjsExpireTime != null && weccjsTokenTime != null) {
			Integer existTime = new Long((new Date().getTime() - weccjsTokenTime.getTime()) / 1000).intValue();
			if (existTime < (weccjsExpireTime - 200))
				return weccjsToken;
		}

		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getWeccToken1() + "&type=jsapi";
		String json = get(url);
		JSONObject object = JSONObject.parseObject(json);

		if (json.contains("40001")) {
			logger.info("wecc token 过期 : " + json);
			if (!weccTokenExceptionSend.equals(getWeccToken1())) {
				SmsApi.send("wecc token 过期,需要手动刷新【wecc】", "15957258049");
				SmsApi.send("wecc token 过期,需要手动刷新【wecc】", "18858281010");
				weccTokenExceptionSend = getWeccToken1();
			}
			throw new NoteException("wecc token 过期");
		}
		// logger.info("获取jstoken 结果json = " + json);
		// 本地缓存token
		// setJsToken(object.getString("ticket"),
		// Integer.parseInt(object.getString("expires_in")));
		this.weccjsToken = object.getString("ticket");
		this.weccjsExpireTime = Integer.parseInt(object.getString("expires_in"));
		weccjsTokenTime = new Date();

		return weccjsToken;
	}

	/**
	 * 获取js_token
	 * 
	 * @return
	 */
	public String getJsToken() {
		// 如果当前存在token并且未过期,返回token
		if (jsToken != null && jsExpireTime != null && jsTokenTime != null) {
			Integer existTime = new Long((new Date().getTime() - jsTokenTime.getTime()) / 1000).intValue();
			if (existTime < (jsExpireTime - 200))
				return jsToken;
		}

		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getToken() + "&type=jsapi";
		String json = get(url);
		JSONObject object = JSONObject.parseObject(json);
		// logger.info("获取jstoken 结果json = " + json);
		// 本地缓存token
		setJsToken(object.getString("ticket"), Integer.parseInt(object.getString("expires_in")));

		return jsToken;
	}

	/**
	 * 设置token和创建时间
	 * @param jsToken
	 * @param jsExpireTime
	 */
	private void setJsToken(String jsToken, Integer jsExpireTime) {
		this.jsToken = jsToken;
		this.jsExpireTime = jsExpireTime;
		jsTokenTime = new Date();
	}

	/**
	 * 获取前台的js_ticket
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public JsTicket getJsTicket(String url) throws Exception {
		JsTicket jt = new JsTicket();
		String noncestr = "chenshujieFat";
		// 时间取秒
		String timestamp = System.currentTimeMillis() / 1000 + "";
		String jstoken = getJsToken();
		String urlDecode = URLDecoder.decode(url, "utf8");
		String sha1 = "jsapi_ticket=" + jstoken + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + urlDecode;

		String signature = sha1(sha1);

		jt.setNoncestr(noncestr);
		jt.setAppId(WeiXinConf.APPID);
		jt.setTimestamp(timestamp);
		jt.setSignature(signature);
		return jt;
	}

	/**
	 * 获取wecc前台的 js_ticket
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public JsTicket getWeccJsTicket(String url) throws Exception {
		JsTicket jt = new JsTicket();
		String noncestr = "chenshujieFat";
		// 时间取秒
		String timestamp = System.currentTimeMillis() / 1000 + "";
		String jstoken = getWeccJsToken1();
		String urlDecode = URLDecoder.decode(url, "utf8");
		String sha1 = "jsapi_ticket=" + jstoken + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + urlDecode;

		String signature = sha1(sha1);

		jt.setNoncestr(noncestr);
		jt.setAppId(WeiXinConf.WECCAPPID);
		jt.setTimestamp(timestamp);
		jt.setSignature(signature);
		return jt;
	}

	public static String createWeccBaseUrl(String state, String redircturl) {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinConf.WECCAPPID + "&redirect_uri=" + redircturl + "&response_type=code&scope=" + WeiXinConf.SCOPE_BASE + "&state="
				+ state + "#wechat_redirect";
		return url;
	}

	public static String createBaseUrl(String state, String redircturl) {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinConf.APPID + "&redirect_uri=" + redircturl + "&response_type=code&scope=" + WeiXinConf.SCOPE_BASE + "&state=" + state
				+ "#wechat_redirect";
		return url;
	}

	public static String createInfoUrl(String state, String redircturl) {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeiXinConf.APPID + "&redirect_uri=" + redircturl + "&response_type=code&scope=" + WeiXinConf.SCOPE_INFO + "&state=" + state
				+ "#wechat_redirect";
		return url;
	}

}